package cn.tanghom.app.oa.service.impl;

import cn.tanghom.app.oa.model.Candidate;
import cn.tanghom.app.oa.model.Position;
import cn.tanghom.app.oa.model.Talent;
import cn.tanghom.app.oa.repository.CandidateRepository;
import cn.tanghom.app.oa.repository.EduExpRepository;
import cn.tanghom.app.oa.repository.PositionRepository;
import cn.tanghom.app.oa.repository.TalentRepository;
import cn.tanghom.app.oa.repository.WorkExpRepository;
import cn.tanghom.app.oa.service.RecruitmentProcessService;
import cn.tanghom.support.db.DynamicDataSourceHolder;
import cn.tanghom.support.page.Pager;
import cn.tanghom.support.web.ContextHolder;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.unbiz.common.bean.BeanCopy;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import lombok.val;
import me.kafeitu.demo.activiti.util.DateConverter;

/**
 * 招聘业务实现，
 * 版本一：由职位触发。更新职位，发布新职位
 * 
 * 版本二：由简历触发。推荐拒绝，上传简历
 *
 * @author tanghom<tanghom@qq.com> on 2016/6/30
 */
@Service
public class RecruitmentProcessServiceImpl implements RecruitmentProcessService {
	
	static final String db_key = "oa";
	//职位全局招聘流程，一个职位接收多个简历，直到人才数达标
	static final String RecruitmentProcess = "recruitmentProcess";
	//仅仅计算职位和候选人的匹配结果，计算结束，流程结束
	static final String MatchProcess = "matchProcess";
	//面试流程，一个职位和一个候选人
	static final String InterviewProcess = "interviewProcess";
	
	
	final Long talentCategoryId = 8L;
	String collection = "hd_talent_resume_receive";		
	
    @Resource
    private PositionRepository respository;
    
    @Resource
    private CandidateRepository candidateRepository;
    
    @Autowired
    private TalentRepository talentRepository;
   	
   	@Autowired
   	WorkExpRepository workExpRepository;	
   	
   	@Autowired
   	EduExpRepository eduExpRepository;
    
    @Resource
    private RuntimeService runtimeService;
    
    @Resource
    protected TaskService taskService;
   
    @Resource
    protected RepositoryService repositoryService;
    
    @Resource
    private IdentityService identityService;
    
   

	

	@Override
	public ProcessInstance startWorkflow(Position entity, Map<String, Object> variables) {		
		if(entity.getId()==null){
			try(val db = DynamicDataSourceHolder.active(db_key)){
				respository.save(entity);
	    	}
		}
    	
        String businessKey = entity.getId().toString();
        ProcessInstance processInstance = null;
        try {
        	String userid=(String) ContextHolder.getSession().getAttribute("username");	
            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(userid);            
            variables.put("position", entity);
            variables.put("positionId", entity.getId());
            if(variables.containsKey("talentId")){            	
            	processInstance = runtimeService.startProcessInstanceByKey(MatchProcess, businessKey+'-'+variables.get("talentId"), variables);
            	String processInstanceId = processInstance.getId();
                entity.setProcessInstanceId(processInstanceId);
                variables = processInstance.getProcessVariables();
            }
            else{
            	processInstance = runtimeService.startProcessInstanceByKey(RecruitmentProcess, businessKey, variables);
            	String processInstanceId = processInstance.getId();
                entity.setProcessInstanceId(processInstanceId);
            	try(val db = DynamicDataSourceHolder.active(db_key)){
                   respository.save(entity);
                }
            }
            
            
        }  
        catch(FlowableException e){
        	throw e;
        }
        finally {
            identityService.setAuthenticatedUserId(null);
        }
       
        return processInstance;
		
	}
	
	@Override
	public ProcessInstance startWorkflow(Candidate entity, Map<String, Object> variables) {
		try(val db = DynamicDataSourceHolder.active(db_key)){
			candidateRepository.save(entity);
    	}
        String businessKey = entity.getId().toString();
        ProcessInstance processInstance = null;
        try {
        	String userid=(String) ContextHolder.getSession().getAttribute("username");	
            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(userid);    
            
            val resume = talentRepository.findOne(entity.getTalentId());
            val pos = respository.findOne(entity.getPositionId());
            variables.put("position", pos);
            variables.put("talent", resume);
            processInstance = runtimeService.startProcessInstanceByKey(InterviewProcess, businessKey, variables);
            
            String processInstanceId = processInstance.getId();
            entity.setProcessInstanceId(processInstanceId);
        } 
        catch(FlowableException e){
        	throw e;
        }
        finally {
            identityService.setAuthenticatedUserId(null);
        }
        try(val db = DynamicDataSourceHolder.active(db_key)){
        	candidateRepository.save(entity);
        }
        return processInstance;
	}
	

	@Override
	public List<Position> getPageDeptTask(String userid, int firstrow, int rowcount) {
		// TODO Auto-generated method stub
		List<Position> results=new ArrayList<Position>();
		List<Task> tasks=taskService.createTaskQuery().taskCandidateGroup("deptLeader").listPage(firstrow, rowcount);
		for(Task task:tasks){
			String instanceid=task.getProcessInstanceId();
			ProcessInstance ins=runtimeService.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
			String businesskey=ins.getBusinessKey();
			Position a = respository.findOne(new Long(businesskey));
			a.setTask(task);
			results.add(a);
		}
		return results;
	}

	@Override
	public List<Position> getPageHrTask(String userid, int firstrow, int rowcount) {
		// TODO Auto-generated method stub
		List<Position> results=new ArrayList<Position>();
		List<Task> tasks=taskService.createTaskQuery().taskCandidateGroup("hr").listPage(firstrow, rowcount);
		for(Task task:tasks){
			String instanceid=task.getProcessInstanceId();
			ProcessInstance ins=runtimeService.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
			String businesskey=ins.getBusinessKey();
			Position a = respository.findOne(new Long(businesskey));
			a.setTask(task);
			results.add(a);
		}
		return results;
	}

	

    @Override
    public void save(Position position) { 
    	try(val db = DynamicDataSourceHolder.active(db_key)){
    		respository.save(position);
    	}
    }

    /**
     * 更新职位，参数可以只带部分字段的数据，会和原职位信息合并
     */
    @Override
    public void update(Position position) {
    	try(val db = DynamicDataSourceHolder.active(db_key)){
			 if(position.getId()!=null){
	         	Position positionOri = respository.findOne(position.getId());
	         	if(positionOri!=null){
	         		BeanCopy.merge(position,positionOri);
	         		position = positionOri;
	         	}
	         }
    		respository.save(position);
    	}
    }

    @Override
    public void delete(Long id) {
    	try(val db = DynamicDataSourceHolder.active(db_key)){
    		respository.delete(id);
    	}
    }

    @Override
    public Position findById(Long id) {
    	try(DynamicDataSourceHolder.Active db = DynamicDataSourceHolder.active(db_key)){
    		return respository.findOne(id);
    	}
    }

    @Override
    public Page<Position> findPageByUserId(Long userId, Integer status, Long index) {
    	try(DynamicDataSourceHolder.Active db = DynamicDataSourceHolder.active(db_key)){
    		
    		PageRequest pager = new PageRequest(index==null? 0: index.intValue(),10,Sort.Direction.DESC, "id");	       
	        Page<Position> leaveList = respository.findByUserId(userId,pager);	      
	      
	        return leaveList;
    	}
    }

   
    public Position findById(String id) {
    	try(DynamicDataSourceHolder.Active db = DynamicDataSourceHolder.active(db_key)){
    		return respository.findOne(Long.parseLong(id));
    	}
    }	
	
	

	public void updateComplete(String taskid, Position leave,String reapply) {
		Task task = taskService.createTaskQuery().taskId(taskid).singleResult();
		String instanceid=task.getProcessInstanceId();
		ProcessInstance ins = runtimeService.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
		String businesskey=ins.getBusinessKey();
		Position a= findById(businesskey);
		
		//a.setStartTime(leave.getStartTime());
		//a.setEndTime(leave.getEndTime());
		
		Map<String,Object> variables=new HashMap<String,Object>();
		variables.put("reapply", reapply);
		if(reapply.equals("true")){
			respository.save(a);
			taskService.complete(taskid,variables);
		}else
			taskService.complete(taskid,variables);
	}

	
}
